package com.sgb.kjwl.view.widget.transport;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.databinding.AppDialogGoodsTypeChooseBinding;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.utils.KeyboardUtils;
import com.sgb.kjwl.view.constant.RouterKey;
import com.sgb.kjwl.view.ui.adapter.transport.GoodsTypeChooseAdapter;
import com.sgb.kjwl.view.ui.adapter.transport.GoodsTypeSearchTagAdapter;
import com.sgb.trip.view.activity.CitySelectionActivity;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.recyclerview.FlowLayoutManager;
import com.swgk.core.util.ArrayUtil;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: 杨畔
 * @date: 2021/11/2 17:57
 * @Description: 货源类型选择弹窗
 */
public class GoodsTypeChooseDialog extends DialogFragment implements View.OnClickListener {
    private static final String TAG_CACHE = "GOODS_TYPE_SEARCH_TAG_CACHE";
    private Context mContext;
    private AppDialogGoodsTypeChooseBinding mBinding;
    //列表适配器
    private List<GoodsInfoTypeEntity3> mOnceTypeList;
    private GoodsTypeChooseAdapter mOnceTypeAdapter;
    private List<GoodsInfoTypeEntity3> mSecondTypeList;
    private GoodsTypeChooseAdapter mSecondAdapter;
    private List<String> mHistoryTagList;
    private GoodsTypeSearchTagAdapter mTagAdapter;
    private List<GoodsInfoTypeEntity3> mSearchList;
    private GoodsTypeChooseAdapter mSearchAdapter;
    //回调接口
    private CallBack mCallBack;
    private Dialog dialog;
    private boolean isInit;

    public interface CallBack {
        void select(GoodsInfoTypeEntity3 entity);
    }

    public GoodsTypeChooseDialog callBack(CallBack callBack) {
        this.mCallBack = callBack;
        return this;
    }

    public static GoodsTypeChooseDialog newInstance(ArrayList<GoodsInfoTypeEntity3> type) {
        Bundle args = new Bundle();
        args.putParcelableArrayList(RouterKey.DATA, type);
        GoodsTypeChooseDialog fragment = new GoodsTypeChooseDialog();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(@NotNull Context context) {
        super.onAttach(context);
        this.mContext = context;
    }

    @NotNull
    @Override
    @SuppressLint("InflateParams")
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        if (!isInit) {
            mBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.app_dialog_goods_type_choose, null, false);
            init();
            dialog = new Dialog(mContext, R.style.MyDialogStyleBottom);
            dialog.setCanceledOnTouchOutside(true);
            dialog.setContentView(mBinding.getRoot());
            dialog.show();
            //设置窗口大小
            Window window = dialog.getWindow();
            if (window != null) {
                window.setGravity(Gravity.CENTER); //可设置dialog的位置
                window.getDecorView().setPadding(0, 0, 0, 0); //消除边距
                WindowManager.LayoutParams lp = window.getAttributes();
                lp.width = WindowManager.LayoutParams.MATCH_PARENT;   //设置宽度充满屏幕
                lp.height = WindowManager.LayoutParams.MATCH_PARENT;
                window.setAttributes(lp);
            }

            isInit = true;
        }
        return dialog;
    }

    private void init() {
        initRecycler();
        initEvent();
        initData();
    }

    private void initRecycler() {
        //一级货物类型
        mOnceTypeList = new ArrayList<>();
        mOnceTypeAdapter = new GoodsTypeChooseAdapter(mOnceTypeList);
        mOnceTypeAdapter.setType(0);
        mBinding.rvOnce.setLayoutManager(new LinearLayoutManager(mContext));
        mOnceTypeAdapter.bindToRecyclerView(mBinding.rvOnce);
        //二级货物类型
        mSecondTypeList = new ArrayList<>();
        mSecondAdapter = new GoodsTypeChooseAdapter(mSecondTypeList);
        mSecondAdapter.setType(1);
        mBinding.rvSecond.setLayoutManager(new LinearLayoutManager(mContext));
        mSecondAdapter.bindToRecyclerView(mBinding.rvSecond);
        //历史搜索tag
        mHistoryTagList = new ArrayList<>();
        mTagAdapter = new GoodsTypeSearchTagAdapter(mHistoryTagList);
        //todo 布局管理替换
        mBinding.rvHistoryTag.setLayoutManager(new FlowLayoutManager());
        mTagAdapter.bindToRecyclerView(mBinding.rvHistoryTag);
        //搜索结果
        mSearchList = new ArrayList<>();
        mSearchAdapter = new GoodsTypeChooseAdapter(mSearchList);
        mBinding.rvSearchResult.setLayoutManager(new LinearLayoutManager(mContext));
        mSearchAdapter.bindToRecyclerView(mBinding.rvSearchResult);
        //设置尾部返回按钮
        setFooter();
    }

    @SuppressLint("InflateParams")
    private void setFooter() {
        View tagFooter = LayoutInflater.from(mContext).inflate(R.layout.app_footer_goods_type_choose, null);
        mTagAdapter.addFooterView(tagFooter);
        View searchFooter = LayoutInflater.from(mContext).inflate(R.layout.app_footer_goods_type_choose, null);
        mSearchAdapter.addFooterView(searchFooter);
        //
        View.OnClickListener listener = v -> {
            mBinding.etSearch.clearFocus();
            mBinding.clHistoryPage.setVisibility(View.GONE);
            mBinding.llGoodsTypePage.setVisibility(View.VISIBLE);
        };
        tagFooter.findViewById(R.id.tv_back_all).setOnClickListener(listener);
        searchFooter.findViewById(R.id.tv_back_all).setOnClickListener(listener);
    }

    private void initEvent() {
        mBinding.setOnClick(this);
        //搜索回调
//        mBinding.etSearch.setOnKeyListener((v, keyCode, event) -> {
//            if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
//                clickSearch();
//                return true;
//            }
//            return false;
//        });
        mBinding.etSearch.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus && mBinding.llGoodsTypePage.getVisibility() == View.VISIBLE) {
                mBinding.llGoodsTypePage.setVisibility(View.GONE);
                mBinding.clHistoryPage.setVisibility(View.VISIBLE);
            }
        });
        //列表回调
        mOnceTypeAdapter.setOnItemClickListener((adapter, view, position) -> {
            GoodsInfoTypeEntity3 entity = mOnceTypeList.get(position);
            mSecondTypeList.clear();
            if (mOnceTypeAdapter.getmSelectIndex()!=position){
                mSecondAdapter.setSelectIndex(-1);
            }
            mOnceTypeAdapter.setSelectIndex(position);

            if (ArrayUtil.isNullOrEmpty(entity.getChildList())) {
                select(entity);
            } else {
                mSecondTypeList.addAll(entity.getChildList());
            }
            mSecondAdapter.notifyDataSetChanged();
        });
        mSecondAdapter.setOnItemClickListener((adapter, view, position) -> {
            GoodsInfoTypeEntity3 entity = mSecondTypeList.get(position);
            mSecondAdapter.setSelectIndex(position);
            mSecondAdapter.notifyDataSetChanged();
            select(entity);
        });
        mSearchAdapter.setOnItemClickListener((adapter, view, position) -> {
            //更新tag
            String keyWord = mBinding.etSearch.getText().toString();
            updateTag(keyWord);
            mBinding.etSearch.setText("");
            mBinding.etSearch.clearFocus();
            mBinding.clHistoryPage.setVisibility(View.GONE);
            mBinding.llGoodsTypePage.setVisibility(View.VISIBLE);
            mOnceTypeAdapter.setSelectIndex(-1);
            mSecondAdapter.setSelectIndex(-1);
            mBinding.rvOnce.scrollToPosition(0);
            mSecondTypeList.clear();
            mSecondAdapter.notifyDataSetChanged();

            GoodsInfoTypeEntity3 entity = mSearchList.get(position);
            select(entity);
        });
        mTagAdapter.setOnItemClickListener((adapter, view, position) -> {
            mBinding.etSearch.setText(mHistoryTagList.get(position));
            clickSearch();
        });

        mBinding.etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    mBinding.clHistoryPage.setVisibility(View.VISIBLE);
                    mBinding.clSearchPage.setVisibility(View.GONE);
                } else {
                    clickSearch();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void initData() {
        if (getArguments() != null) {
            mOnceTypeList.clear();
            List<GoodsInfoTypeEntity3> list = getArguments().getParcelableArrayList(RouterKey.DATA);
            if (ArrayUtil.isNotNullAndEmpty(list)) {
                mOnceTypeList.addAll(list);
            }
            mOnceTypeAdapter.notifyDataSetChanged();
        }
        //获取历史搜索记录
        getTagCache();
    }

    /**
     * 点击搜索
     */
    private void clickSearch() {
//        KeyboardUtils.hideSoftInput(mBinding.etSearch);
        //
        mBinding.clHistoryPage.setVisibility(View.GONE);
        mBinding.clSearchPage.setVisibility(View.VISIBLE);
        mBinding.tvHistoryTip.setVisibility(View.VISIBLE);
        mBinding.ivHistoryClear.setVisibility(View.VISIBLE);
        String keyWord = mBinding.etSearch.getText().toString();
        search(keyWord);
    }

    private void select(GoodsInfoTypeEntity3 entity) {
        if (mCallBack != null) {
            mCallBack.select(entity);
        }
        dismiss();
    }

    /**
     * 获取历史搜索记录
     */
    private void getTagCache() {
        String cache = MkvUtils.get().getString(TAG_CACHE);
        if (TextUtils.isEmpty(cache)) {
            mBinding.tvHistoryTip.setVisibility(View.GONE);
            mBinding.ivHistoryClear.setVisibility(View.GONE);
            return;
        }
        mBinding.tvHistoryTip.setVisibility(View.VISIBLE);
        mBinding.ivHistoryClear.setVisibility(View.VISIBLE);
        List<String> list = new Gson().fromJson(cache, new TypeToken<List<String>>() {
        }.getType());
        mHistoryTagList.clear();
        if (ArrayUtil.isNotNullAndEmpty(list)) {
            mHistoryTagList.addAll(list);
        }
        mTagAdapter.notifyDataSetChanged();
    }

    /**
     * 更新tag
     */
    private void updateTag(String tag) {
        if (TextUtils.isEmpty(tag)) {
            return;
        }
        //检查是否包含该搜索内容
        if (mHistoryTagList.contains(tag)) {
            mHistoryTagList.remove(tag);
            mHistoryTagList.add(0, tag);
            mTagAdapter.notifyDataSetChanged();
            return;
        }
        //检查是否超出20个内容,多余的删除末尾
        if (mHistoryTagList.size() >= 20) {
            mHistoryTagList.remove(mHistoryTagList.size() - 1);
        }
        mHistoryTagList.add(0, tag);
        mTagAdapter.notifyDataSetChanged();
    }

    /**
     * 保存搜索记录
     */
    private void saveTagCache(List<String> list) {
        if (ArrayUtil.isNullOrEmpty(list)) {
            MkvUtils.get().putString(TAG_CACHE, "");
        } else {
            MkvUtils.get().putString(TAG_CACHE, new Gson().toJson(list));
        }
    }

    /**
     * 搜索
     */
    public void search(String keyWord) {
//        DialogHelper.showProgressDialog(mContext, "数据加载中...");
        NewAPIManager.getInstance().getLogisticsAPI().searchGoodsType(keyWord).enqueue(new ICallBack<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
            @Override
            public void onSuccess(BaseEntity<List<GoodsInfoTypeEntity3>> data) {
//                DialogHelper.dismissProgressDialog();
                syncSearch(data.getData());
            }
        });
    }

    private void syncSearch(List<GoodsInfoTypeEntity3> list) {
        mSearchList.clear();
        if (ArrayUtil.isNotNullAndEmpty(list)) {
            mSearchList.addAll(list);
        }
        mSearchAdapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View v) {
        KeyboardUtils.hideSoftInput(mBinding.etSearch);
        if (v == mBinding.tvCancel) {
            dismiss();
        } else if (v == mBinding.ivHistoryClear) {
            mHistoryTagList.clear();
            mTagAdapter.notifyDataSetChanged();
            mBinding.tvHistoryTip.setVisibility(View.GONE);
            mBinding.ivHistoryClear.setVisibility(View.GONE);
        }
    }

    @Override
    public void onDismiss(@NonNull @NotNull DialogInterface dialog) {
        super.onDismiss(dialog);
        saveTagCache(mHistoryTagList);
    }
}
